package com.smartfast4j.backend.common.controller;

import com.smartfast4j.backend.common.bean.R;
import com.smartfast4j.backend.common.exception.SmartFast4jException;
import com.smartfast4j.backend.common.util.ShiroUtils;
import com.smartfast4j.backend.modules.sys.entity.SysUser;
import org.apache.log4j.Logger;
import org.apache.shiro.authz.AuthorizationException;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

/**
 * Created by gacl on 2017/3/3.
 */
public class WebBaseController {

    protected  Logger logger = Logger.getLogger(getClass());

    /** 基于@ExceptionHandler异常处理 */
    @ExceptionHandler
    @ResponseBody
    public R exp(HttpServletResponse response,Exception ex) {
        R r = new R();
        try {
            response.setContentType("application/json;charset=utf-8");
            response.setCharacterEncoding("utf-8");
            if (ex instanceof SmartFast4jException) {
                r.put("code", ((SmartFast4jException) ex).getCode());
                r.put("msg", ((SmartFast4jException) ex).getMessage());
            }else if(ex instanceof DuplicateKeyException){
                r = R.error("数据库中已存在该记录");
            }else if(ex instanceof AuthorizationException){
                r = R.error("没有权限，请联系管理员授权");
            }else{
                r = R.error();
            }
            //记录异常日志
            logger.error(ex.getMessage(), ex);
        } catch (Exception e) {
            logger.error("RRExceptionHandler 异常处理失败", e);
        }
        //记录错误信息
        logger.error(ex.getMessage(), ex);
        return r;
    }

    /**
     * 客户端重定向
     *
     * @param url
     * @return
     */
    protected String redirect(String url) {
        return "redirect:" + url;
    }

    /**
     * 服务端重定向
     *
     * @param url
     * @return
     */
    protected String forward(String url) {
        return "forward:" + url;
    }


    /**
     * 获取当前登录的系统用户
     * @return
     */
    protected SysUser getSysLoginUser() {
        return ShiroUtils.getLoginSysUser();
    }

    /**
     * 登录用户的ID
     * @return
     */
    protected Long getSysLoginUserId() {
        return getSysLoginUser().getUserId();
    }
}
